<?php

class TransactionController extends Controller {

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
//	public $layout='//layouts/column2';
    public $layout = '//layouts/eastsouthwest';

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('index', 'view'),
                'users' => array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('create', 'update', 'autocomplete', 'contra', 'addrow', 'initrow', 'mygrid', 'autocompleteAcledger', 'init', 'accountingvouchers'),
                'users' => array('@'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array('popupview', 'admin', 'delete'),
                'users' => array('admin'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    public function actionMygrid() {
        //echo $this->getColumns();
    }

    public function gridOpeningbalancecrdr($data, $row) {
        $res = $this->widget('zii.widgets.jui.CJuiAutoComplete', array(
            'name' => 'transactiondetails[' . $row . '][openingbalancecrdr]',
            'value' => $data['openingbalancecrdr'],
            'theme' => 'bgscstpc',
            'source' => array('CR', 'DR'),
            'htmlOptions' => array(
                'onchange' => 'alert("hii");'
            //'class' => 'date'
            )
                ), true);
        return $res;
    }

    public function gridAcledger($data, $row) {

        $res = $this->widget('zii.widgets.jui.CJuiAutoComplete', array(
            'name' => 'transactiondetails[' . $row . '][acledger]',
            'value' => $data['acledger'],
            //'model' => $model, 
            //'id' => 'Acledger_acgroupname',
            'theme' => 'bgscstpc',
            'source' => $this->createUrl('acledger/autocomplete'),
            // additional javascript options for the autocomplete plugin
            'options' => array(
                'showAnim' => 'fold',
            ),
            'htmlOptions' => array(
            )
                ), true);
        return $res;
    }

    public function actionAutocomplete() {
        $res = array();

        if (isset($_GET['term'])) {
            $match = addcslashes($_GET['term'], '%_');
            $criteria = new CDbCriteria(array(
                        'condition' => 'transactionmastervoucherdate LIKE :transactionmastervoucherdate',
                        'params' => array(':transactionmastervoucherdate' => "%$match%")
                            ));
            $models = Transaction::model()->findAll($criteria);
            foreach ($models as $model) {
                $res[] = $model->transactionmastervoucherdate;
            }
        }

        echo CJSON::encode($res);
    }

    public function actionAutocompleteAcledger() {
        $res = array();

        if (isset($_GET['term'])) {
            $type = isset($_GET['type']) ? $_GET['type'] : '';
            $transactioncrdr = isset($_GET['transactioncrdr']) ? $_GET['transactioncrdr'] : '';
            $rulescolumn = strtolower($type . $transactioncrdr);

            $match = addcslashes($_GET['term'], '%_');
            $criteria = new CDbCriteria(array(
                        'with' => array('idacgroup0', 'idacgroup0.idrules0'),
                        'condition' => 'acledgername LIKE :acledgername And idrules0.' . $rulescolumn . '=1',
                        'params' => array(':acledgername' => "%$match%")
                            ));
            $models = Acledger::model()->findAll($criteria);
            foreach ($models as $model) {
                $res[] = $model->acledgername;
            }
        }
        echo CJSON::encode($res);
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id) {
        if (isset($_REQUEST['isAjaxRequest']) && $_REQUEST['isAjaxRequest'] == 1) {
            Yii::app()->clientscript->scriptMap['jquery.js'] = false;
            Yii::app()->clientscript->scriptMap['jquery-ui.min.js'] = false;
            echo $this->renderPartial('view', array('model' => $this->loadModel($id)), true, true);
            Yii::app()->end();
            exit();
        } else {
            $this->render('view', array(
                'model' => $this->loadModel($id),
            ));
        }
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate() {
        $model = new Transaction;

        // Uncomment the following line if AJAX validation is needed
        $this->performAjaxValidation($model);

        if (isset($_POST['Transaction'])) {
            $model->attributes = $_POST['Transaction'];
            $status = 'Failure';
            if ($model->save()) {
                $status = 'Success';
            }

            echo CJSON::encode(array(
                'status' => $status,
            ));
            exit;
        } else {
            if (isset($_REQUEST['isAjaxRequest']) && $_REQUEST['isAjaxRequest'] == 1) {
                Yii::app()->clientscript->scriptMap['jquery.js'] = false;
                Yii::app()->clientscript->scriptMap['jquery-ui.min.js'] = false;
                echo $this->renderPartial('_form', array('model' => $model), true, true);
                exit();
            }
        }
    }

    public $myn = 3;
    public $row = 1;

    public function actionAddrowOld() {
//            if(isset(Yii::app()->session['rowcount'])){
//                Yii::app()->session['rowcount'] = Yii::app()->session['rowcount'] + 1;
//            }
//            else{
//                Yii::app()->session['rowcount'] = 1;
//            }
//            Yii::app()->session['rowcount'] = Yii::app()->session['rowcount'] + 1;
//            $rawData = Yii::app()->session['rawdata'];
        //$rawData[] = array('id' => 0, 'openingbalancecrdr' => 'CR');            
        //$rawData[]['id'] = count($rawData) + 1;
        $rawData = array();
//            $rawData[]['openingbalancecrdr'] = 'CR';
        if (isset($_POST['transactiondetails'])) {
            print_r($_POST['transactiondetails']);
            //$rawData[0]['id'] = print_r($_POST['transactiondetails'], true);
            foreach ($_POST['transactiondetails'] as $key => $value) {
                //echo $key . ' - ' . $value['id'] . ' - ' . print_r($value, true) . '\n';
                $rawData[$key]['id'] = $value['id'];
                $rawData[$key]['openingbalancecrdr'] = $value['openingbalancecrdr'];
                $rawData[$key]['acledger'] = $value['acledger'];
            }
            $rawData[count($rawData)] = array('id' => count($rawData), 'openingbalancecrdr' => $_POST['f1'], 'acledger' => '');
        }
        Yii::app()->session['rawdata'] = $rawData;
        echo CJSON::encode(array(
            'status' => 'Success',
        ));
        exit;
    }

    public function getCredit() {
        $rawData = Yii::app()->session['rawdata'];
        $credit = 0;
        foreach ($rawData as $row) {
            $credit += $row['credit'];
        }
        return number_format((float) $credit, 2, '.', '');
    }

    public function getDebit() {
        $rawData = Yii::app()->session['rawdata'];
        $debit = 0;
        foreach ($rawData as $row) {
            $debit += $row['debit'];
        }
        return number_format((float) $debit, 2, '.', '');
    }

    public function actionAddrow() {
        $rawData = Yii::app()->session['rawdata'];
//            echo 'hii' . $_POST['id']; exit;
        $transactionAmount = number_format((float) $_POST['transactionamount'], 2, '.', '');
        if ($_POST['id'] >= 0) {
            $rawData[$_POST['id']] = array('id' => $_POST['id'], 'openingbalancecrdr' => $_POST['transactioncrdr'], 'acledger' => $_POST['acledger'], 'transactionamount' => $transactionAmount, 'credit' => $_POST['transactioncrdr'] == 'CR' ? $transactionAmount : '', 'debit' => $_POST['transactioncrdr'] == 'DR' ? $transactionAmount : '');
        } else {
            $rawData[count($rawData)] = array('id' => count($rawData), 'openingbalancecrdr' => $_POST['transactioncrdr'], 'acledger' => $_POST['acledger'], 'transactionamount' => $transactionAmount, 'credit' => $_POST['transactioncrdr'] == 'CR' ? $transactionAmount : '', 'debit' => $_POST['transactioncrdr'] == 'DR' ? $transactionAmount : '');
        }


//            if(isset($_POST['transactiondetails'])){
//                print_r($_POST['transactiondetails']);
//                //$rawData[0]['id'] = print_r($_POST['transactiondetails'], true);
//                foreach($_POST['transactiondetails'] as $key=>$value){
//                    //echo $key . ' - ' . $value['id'] . ' - ' . print_r($value, true) . '\n';
//                    $rawData[$key]['id'] = $value['id'];
//                    $rawData[$key]['openingbalancecrdr'] = $value['openingbalancecrdr'];                    
//                    $rawData[$key]['acledger'] = $value['acledger'];                    
//                }                
//                $rawData[count($rawData)] = array('id' => count($rawData), 'openingbalancecrdr' => $_POST['f1'], 'acledger'=>'');
//            }            
        Yii::app()->session['rawdata'] = $rawData;
        echo CJSON::encode(array(
            'status' => 'Success',
            'credit' => $this->getCredit(),
            'debit' => $this->getDebit(),
        ));
        exit;
    }

    public function actionInit() {
        Yii::app()->session['rowcount'] = 1;
        Yii::app()->session['rawdata'] = NULL;
    }

    public function actionInitrow() {
        //Yii::app()->session['rowcount'] = 1;
        $rawData[]['id'] = 0;
        Yii::app()->session['rawdata'] = $rawData;
        echo CJSON::encode(array(
            'status' => 'Success',
        ));
        exit;
    }

    public function getColumns() {

        $model = new Transaction;
        $dataProvider = $model->transactiondetailsDataProvider();

        $columns = array(
            array(
                'name' => 'id',
                'value' => 'CHtml::textField("transactiondetails[" . $data[\'id\'] . "][id]", $data[\'id\'], array(\'width\'=>20,\'size\'=>7,\'maxlength\'=>30,\'style\'=>\'text-align:right\'))',
                'type' => 'raw',
            ),
            //        array(
            //            'name' => 'openingbalancecrdr',
            ////            'value' => 'CHtml::textField("transactiondetails[" . $data[\'id\'] . "][openingbalancecrdr]", $data[\'openingbalancecrdr\'], array(\'width\'=>20,\'size\'=>7,\'maxlength\'=>30,\'style\'=>\'text-align:right\'))',
            //            'value' => 'CHtml::dropDownList("transactiondetails[" . $data[\'id\'] . "][openingbalancecrdr]",$data[\'openingbalancecrdr\'],array(\'CR\'=>\'CR\', \'DR\'=>\'DR\'))',
            //            'type' => 'raw',
            //        ),        
            array(
                'name' => 'openingbalancecrdr',
                'type' => 'raw',
                'value' => array($this, 'gridOpeningbalancecrdr'),
            ),
            array(
                'name' => 'acledger',
                'type' => 'raw',
                //            'value'=>array($this,'gridAcledger'), 
                'value' => 'CHtml::textField("transactiondetails[" . $data[\'id\'] . "][acledger]", $data[\'acledger\'], array(\'width\'=>20,\'size\'=>7,\'maxlength\'=>30,\'style\'=>\'text-align:right\'))',
            ),
                //    echo $form->dropDownList($model,'openingbalancecrdr',array('CR'=>'CR', 'DR'=>'DR'));        
        );

        $wid = $this->widget('ext.eziiui.widgets.grid.CGridViewUI', array(
//            $wid = $this->widget('ext.EDataTables.EDataTables', array(
            'id' => 'transaction-grid',
            'dataProvider' => $dataProvider,
            'columns' => $columns,
            //'enablePagination' => false,
            'summaryText' => '',
                //        'filter' => $filtersForm,
                ));
        return $wid;
    }

//    public function actionContra($n = 1) {
//        if ($n > 1) {
//            $this->myn = $n;
//        }
//        $this->myn++;
//        $model = new Transaction;
//
//        // Uncomment the following line if AJAX validation is needed
//        $this->performAjaxValidation($model);
//
//        if (isset($_POST['Transaction'])) {
//            $model->attributes = $_POST['Transaction'];
//            $status = 'Failure';
//            if ($model->save()) {
//                $status = 'Success';
//            }
//
//            echo CJSON::encode(array(
//                'status' => $status,
//            ));
//            exit;
//        } else {
////                    if (isset($_REQUEST['init']) && $_REQUEST['init'] == 1) {
////                        Yii::app()->session['rowcount'] = 1;                        
////                    }
//
//            if (isset($_REQUEST['isAjaxRequest']) && $_REQUEST['isAjaxRequest'] == 1) {
////                        Yii::app()->clientscript->scriptMap['jquery.js'] = false;
////                        Yii::app()->clientscript->scriptMap['jquery-ui.min.js'] = false;
//
//                $model->idvouchertype = 1;
//                echo $this->renderPartial('_form', array('model' => $model, 'dataProvider' => $model->transactiondetailsDataProvider(), 'type' => 'contra'), true, true);
//                exit();
//            }
//        }
//    }

    public function actionAccountingvouchers($idtransactionmaster = 0, $idvouchertype = 0) {
        
        $model = new Transaction;
        
        // Uncomment the following line if AJAX validation is needed
        $this->performAjaxValidation($model);

        if (isset($_POST['Transaction'])) {
            $model->attributes = $_POST['Transaction'];
            $status = 'Failure';
            if ($model->save()) {
                $status = 'Success';
            }

            echo CJSON::encode(array(
                'status' => $status,
            ));
            exit;
        } else {

            if (isset($_REQUEST['isAjaxRequest']) && $_REQUEST['isAjaxRequest'] == 1) {

                if($idtransactionmaster > 0){
                    $transactionmaster =  Transactionmaster::model()->find('idtransactionmaster=:idtransactionmaster', array(':idtransactionmaster'=>$idtransactionmaster));
                    if(isset($transactionmaster)){
                        $model->idvouchertype = $transactionmaster->idvouchertype;
                        $vouchertype = $transactionmaster->idvouchertype0->vouchertype;
                    }
                }
                else{
                    if($idvouchertype > 0){
                        $vouchertype =  Vouchertype::model()->find('idvouchertype=:idvouchertype', array(':idvouchertype'=>$idvouchertype));
                        if(isset($vouchertype)){
                            $model->idvouchertype = $vouchertype->idvouchertype;
                            $vouchertype = $vouchertype->vouchertype;
                        }
                    }                    
                }
//                if(isset($transactionmaster)){
//                }
//                else{
//                    $model->idvouchertype = 1;
//                    $vouchertype = 'Contra';
//                }
                echo $this->renderPartial('_form', array('model' => $model, 'dataProvider' => $model->transactiondetailsDataProvider($idtransactionmaster), 'type' => $vouchertype), true, true);
                exit();
            }
        }
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id) {
        $model = $this->loadModel($id);

        // Uncomment the following line if AJAX validation is needed
        $this->performAjaxValidation($model);

        if (isset($_POST['Transaction'])) {
            $model->attributes = $_POST['Transaction'];
            $status = 'Failure';
            if ($model->save()) {
                $status = 'Success';
            }

            echo CJSON::encode(array(
                'status' => $status,
            ));
            exit;
        } else {
            if (isset($_REQUEST['isAjaxRequest']) && $_REQUEST['isAjaxRequest'] == 1) {
                Yii::app()->clientscript->scriptMap['jquery.js'] = false;
                Yii::app()->clientscript->scriptMap['jquery-ui.min.js'] = false;
                echo $this->renderPartial('_form', array('model' => $model), true, true);
                exit();
            }
        }
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id) {
        if (Yii::app()->request->isPostRequest) {
            // we only allow deletion via POST request
            $this->loadModel($id)->delete();

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if (!isset($_GET['ajax']))
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
        }
        else
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Lists all models.
     */
    public function actionIndex() {
        $dataProvider = new CActiveDataProvider('Transaction');
        $this->render('index', array(
            'dataProvider' => $dataProvider,
        ));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        $model = new Transaction('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['Transaction']))
            $model->attributes = $_GET['Transaction'];

        if (isset($_REQUEST['isAjaxRequest']) && $_REQUEST['isAjaxRequest'] == '1') {
            $this->renderPartial('admin', array('model' => $model, 'isAjaxRequest' => $_REQUEST['isAjaxRequest']), false, true);
        } else {
            $this->render('admin', array(
                'model' => $model,
            ));
        }
    }

    /**
     * Manages popupview.
     */
    public function actionPopupview() {
        $model = new Transaction('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['Transaction']))
            $model->attributes = $_GET['Transaction'];

        $params = array(
            'model' => $model,
            'id' => isset($_REQUEST['id']) ? $_REQUEST['id'] : '',
            'isAjaxRequest' => 1,
        );

        Yii::app()->clientscript->scriptMap['jquery.js'] = false;
        if (isset($_REQUEST['isAjaxRequest']) && $_REQUEST['isAjaxRequest'] == '1') {
            //        if (!isset($_GET['ajax'])){
            $this->renderPartial('popupview', $params, false, true);
            Yii::app()->end();
        } else {
            $this->render('popupview', $params);
        }
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id) {
        $model = Transaction::model()->findByPk((int) $id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'transaction-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

}
